#import "FDDiePushButton.h"
#include <libc.h>
#include <math.h>

@implementation FDDiePushButton

- (id)initWithFrame:(struct CGRect)frame {
	if ((self == [super initWithFrame: frame]) != nil) 
	{
		srandom(time(0));
		[self newDie];
	}
	return self;
}

- (void)newDie {
	[self setValue:0];
	[self updateWithValue:[self value]];
}

#pragma mark Roll Methods

- (void)roll {
	NSTimer		*animTimer = [NSTimer scheduledTimerWithTimeInterval:0.05
											  	  target:self
												selector:@selector(animateButtonImages:)
												userInfo:nil
											 	 repeats:YES];
}

- (void)animateButtonImages:(NSTimer *)aTimer {
	if (_animCount >= 9) {
		[aTimer invalidate];
		_animCount = 0;
		int r = (random() % (5-0+1)) + 0;
		[self setValue:r];
		[self updateWithValue:[self value]];
	} else {
		int r = (random() % (5-0+1)) + 0;
		[self updateWithValue:r];
		_animCount = _animCount + 1;
	}
}

- (void)updateWithValue:(int)val {
	[self setImage:[self dieImageWithValue:val downImage:NO] forState:0];
	[self setImage:[self dieImageWithValue:val downImage:YES] forState:1];	
}

- (UIImage *)dieImageWithValue:(int)val downImage:(BOOL)down {

	NSString		*name;
	NSString		*path;
	
	switch (val) {
		case 0:
		name = @"one";
		break;
		case 1:
		name = @"two";
		break;
		case 2:
		name = @"three";
		break;
		case 3:
		name = @"four";
		break;
		case 4:
		name = @"five";
		break;
		case 5:
		name = @"six";
		break;
	}
	
	if (down) {
		return [UIImage applicationImageNamed:[NSString stringWithFormat:@"%@_d.png",name]];
	} else {
		return [UIImage applicationImageNamed:[NSString stringWithFormat:@"%@.png",name]];
	}
}

#pragma mark Accessors

- (int)value {
	return value;
}

- (void)setValue:(int)val {
	value = val;
	[self updateWithValue:val];
}

- (BOOL)held
{
	return held;
}

- (void)setHeld:(BOOL)newHeld
{
	if (newHeld) {
		[self setImage:[self dieImageWithValue:[self value] downImage:NO] forState:1];
		[self setImage:[self dieImageWithValue:[self value] downImage:YES] forState:0];
	} else {
		[self setImage:[self dieImageWithValue:[self value] downImage:NO] forState:0];
		[self setImage:[self dieImageWithValue:[self value] downImage:YES] forState:1];	
	}
	
	held = newHeld;
}
- (void)dealloc
{
	[super dealloc];
}

@end